package com.luxsoft.sw3.cfd;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperPrint;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.luxsoft.sw3.cfd.model.ComprobanteFiscal;
import com.luxsoft.sw3.services.Services;
import com.luxsoft.utils.LoggerHelper;

/**
 * Varias utilerias para la impreion de CFDs
 * 
 * @author Ruben Cancino
 *
 */
public class CFDPdfUtils {
	
	static Logger logger=LoggerHelper.getLogger();
	
	public static File generarPdf(ComprobanteFiscal cfdi) throws Exception{
		
		URL url=new URL(cfdi.getXmlPath());
		File xml=new File(url.toURI());
		
		File dir=xml.getParentFile();
		String fileName=StringUtils.replace(xml.getName(), ".xml", ".pdf");
		
        File pdf = new File(dir,fileName);            
        //OutputStream out = new FileOutputStream(file);
		
		JasperPrint jasperPrint=Services.getInstance().getCFDIPrintServices().impripirComprobante(cfdi);
		FileOutputStream fout=new FileOutputStream(pdf);
		JasperExportManager.exportReportToPdfStream(jasperPrint,fout);
		return pdf;
	}
	
	private static String dirPath;
	
	public static String getDirPath(){
		if(StringUtils.isBlank(dirPath)){
			dirPath=System.getProperty("cfd.pdf.dir", "z:\\CFD\\pdf\\");
		}
		return dirPath;
	}
	
	static DateFormat df=new SimpleDateFormat("yyyy_MM_dd");
	
	public static File getStandarFile(ComprobanteFiscal cfd){
		String fileName=cfd.getSerie()+cfd.getFolio()+".pdf";
		File pdfsDir=new File(CFDPdfUtils.getDirPath()+df.format(cfd.getLog().getCreado()));
		if(!pdfsDir.exists()){
			pdfsDir.mkdir();
		}
		File pdfFile=new File(pdfsDir,fileName);
		return pdfFile;
	}

}
